<?php
defined('BASEPATH') OR exit('No direct script access allowed');
header("Content-type:text/html; charset=UTF-8");
require_once APPPATH.'/libraries/dysms_php/api_demo/SmsDemo.php';

class AuthService extends MY_Controller {
	public function __construct(){
		parent::__construct();
		$this->load->helper(array('form','url'));

        $this->load->model('User_model', 'User');
        $this->load->model('AdminUser_model', 'AdminUser');
        $this->load->model('SMS_model', 'SMS');
        $this->load->model('Log_Model', 'Log');
	}

    /**
     * SMS GET
     */

    public function smsSend(){
        $mobile = $this->input->post('phone',true);
        $code = mt_rand(100000,999999);

        $response = SmsDemo::sendSms( $mobile, $code );
        if($response->Code == "OK"){
            $data = array( 'phone' => $mobile, 'sms_code' => $code, 'add_time' => date("Y-m-d H:i:s") );
            $id =  $this->SMS->add($data);

            echo(json_encode(array( "code" => "success", "message" => "发送成功!", 'id' => $id )));
        }
        else{
            $log = array( 'phone' => $mobile, 'sms_code' => $code, 'msg' => $response->Message, 'add_time' => date("Y-m-d H:i:s") );
            $this->Log->add($log);

            echo(json_encode(array( "code" => "error", "message" => '系统错误' )));
        }


        //$users = $this->User->getManyByCondition( '*', array('phone' => $mobile), null );
        //if( count($users) == 0 ){
        //    echo(json_encode(array( "code" => "error", "message" => "手机号未注册!" )));
        //    return;
        //}

        //$clapi  = new ChuanglanSmsApi();
        //$code = mt_rand(100000,999999);
        //$msg = "【拓风科技】您好，您的验证码".$code; //设置您要发送的内容：其中“【】”中括号为运营商签名符号，多签名内容前置添加提交
        //$result = $clapi->sendSMS($mobile,$msg,'true' );

        //if(!is_null(json_decode($result))){
        //    $output = json_decode($result,true);

        //    if(isset($output['code'])  && $output['code']=='0'){
        //        $data = array( 'phone' => $mobile, 'sms_code' => $code, 'add_time' => date("Y-m-d H:i:s") );
        //        $id =  $this->SMS->add($data);

        //        echo(json_encode(array( "code" => "success", "message" => "发送成功!", 'id' => $id )));
        //    }else{
        //        echo(json_encode(array( "code" => "error", "message" => $output['errorMsg'] )));
        //    }
        //}else{
        //    echo(json_encode(array( "code" => "error", "message" => '系统错误' )));
        //}
    }

    /**
     * SMS jiaoyan
     */

    public function smsPost(){
        $phone = $this->input->post('phone',true);
        $sms = $this->input->post('sms',true);
        $pas = $this->input->post('pas',true);
        $id = $this->input->post('id',true);

        $list = $this->SMS->getManyByCondition( '*', array('id' => $id), null );

        if(count($list) == 0){
            echo(json_encode(array( "code" => "error", "message" => '验证码错误' )));
            return;
        }
        if( $list[0]['sms_code'] != $sms || $list[0]['phone'] != $phone){
            echo(json_encode(array( "code" => "error", "message" => '验证码错误' )));
            return;
        }

        $this->User->update_common_by_array( array( 'phone' => $phone ),array( 'pass' => $pas ) );

        echo(json_encode(array( "code" => "success" )));
    }




    /**
	 * Login Post
	 */
	public function loginPost(){
		$phone = $this->input->post('phone',true);
		$password = $this->input->post('password',true);
        /**$isMbPhone=isMobliePhone($phone);
      if($isMbPhone=false){
             echo(json_encode(array( "code" => "error", "message" => "手机号格式错误!" )));
             return;
         }**/


		if(empty($phone) || empty($password)){
            echo(json_encode(array( "code" => "error", "message" => "手机号或密码错误!" )));
            return;
        }

        else{
            $users = $this->User->getManyByCondition( '*', array('phone' => $phone), null );
            if( count($users) == 0 ){
                echo(json_encode(array( "code" => "error", "message" => "手机号未注册!" )));
                return;
            }
            $users = $this->User->getManyByCondition( '*', array('phone' => $phone, 'pass' => $password), null );
            if( count($users) == 0 ){
                echo(json_encode(array( "code" => "error", "message" => "手机号或密码错误!" )));
                return;
            }

            if(intval($users[0]['status']) == -1){
                echo(json_encode(array( "code" => "error", "message" => "该账号已被禁用!" )));
                return;
            }

            $this->session->currentUser = array(
                                                "has_login" => "true",
                                                "display_name" => "",
                                                "username" => $users[0]['user_name'],
                                                "email" => "",
                                                "role" => $users[0]['role'],
                                                "user_id" => $users[0]['id'],
                                                "phone" => $users[0]['phone'],
                                                "token" => $users[0]['token'],
                                                "group_id" => $users[0]['group_id'],
                                                "user_headimg" => "",
                                                "add_time" => $users[0]['add_time']

                                           );
            $redirectUrl = base_url("user/profile");

            echo(json_encode(array( "code" => "success", "message" => "", "redirectUrl" => $redirectUrl )));
        }
	}

    public function loginAdminPost(){
        $phone = $this->input->post('phone',true);
		$password = $this->input->post('password',true);


		if(empty($phone) || empty($password)){
            echo(json_encode(array( "code" => "error", "message" => "用户名或密码错误!" )));
            return;
        }

        $users = $this->AdminUser->getManyByCondition( '*', array('user_name' => $phone, 'pass' => $password, 'role' => 'admin'), null );
        if( count($users) == 0 ){
            echo(json_encode(array( "code" => "error", "message" => "用户名或密码错误!" )));
            return;
        }

        $this->session->currentUser = array(
                                "has_login" => "true",
                                "display_name" => "",
                                "username" => $users[0]['user_name'],
                                "email" => "",
                                "role" => 'admin',
                                "user_id" => 0,
                                "phone" => 0,
                                "token" => '',
                                "parent_id" => 0,
                                "user_headimg" => "",
                                "add_time" => ''

                           );
        $redirectUrl = base_url("admin/index");

        echo(json_encode(array( "code" => "success", "message" => "", "redirectUrl" => $redirectUrl )));
    }

    /**
     * Register Post
     */
	public function registerPost(){
	    $username = $this->input->post('username',true);
        $phone = $this->input->post('phone',true);
        $student_id = $this->input->post('student_id',true);
        $tutor = $this->input->post('tutor',true);
	    $pass = $this->input->post('pass',true);

        $group_id = $this->input->post('group_id',true);
        $group_name = $this->input->post('group_name',true);


	    if(empty($username) || empty($phone) || empty($pass)){
            echo(json_encode(array( "code" => "error", "message" => "用户名、手机号或密码不能为空! " )));
	        exit();
	    }

	    $users = $this->User->checkUniqueUser($username, $phone);
	    foreach ($users as $v) {
	        if($phone == $v['phone']){
                echo(json_encode(array( "code" => "error", "message" => "手机号已经被注册!" )));
	            exit();
	        }
	    }

	    $data = array(
	        'user_name' => $username,
	        'phone' => $phone,
            'student_id' => $student_id,
            'tutor' => $tutor,
	        'pass' => $pass,
            'group_id' => $group_id,
            'group_name' => $group_name,
            "avatar_url" => "",
	        'token' => $phone."-".time(),
	        'role' => 'common',
	        'status'=>'0',
            'add_time' => date("Y-m-d H:i:s"),
	        );

	    $retUserID = $this->User->add($data);

        $this->session->currentUser = array(
                                    "has_login" => "true",
                                    "display_name" => "",
                                    "username" => $username,
                                    "email" => "",
                                    "role" => "common",
                                    "user_id" => $retUserID,
                                    "phone" => $phone,
                                    "token" => $data['token'],
                                    'group_id' => $group_id,
                                    "user_headimg" => "",
                                    "add_time" => $data['add_time']
                               );

        echo(json_encode(array( "code" => "success", "message" => "注册成功!" )));


	}

    /**
     * 验证手机号格式
     */
    public function isMobliePhone($p){

        if(!is_numeric($p)){
            return false;
        }

        return preg_match('#^13[\d]{9}$|^14[5,7]{1}\d{8}$|^15[^4]{1}\d{8}$|^17[0,6,7,8]{1}\d{8}$|^18[\d]{9}$#',$p)?true:false;
    }




    /**
     * Edit Post
     */
    public function editPost(){
        $pass = $this->input->post('pass',true);
        $user_id = $this->getLoginUserId();

        if( $user_id != 0 ){
            $this->User->update_common_by_array( array( 'id' => $user_id ), array( 'pass' => $pass, 'last_update_time' => date("Y-m-d H:i:s") ) );
        }
        echo(json_encode(array( "code" => "success", "message" => "修改成功!" )));
    }


    /**
     * EditName Post
     */
    public function editnamePost(){
        $username = $this->input->post('username',true);

        $user_id=$this->session->currentUser['user_id'];

        //$id = $this->input->post('id',true);
        if( $user_id != 0 ){
            $this->User->update_by_sql( "update pro_user set pass =$username where id=$user_id");
        }
        echo(json_encode(array( "code" => "success", "message" => "修改成功!" )));
    }



    public function test(){
        return "test";
    }
}